import ax from '../common/ax2'
import action from './actions'
import { trim } from '@/common/stringutil.js'
import { getListItemByKey } from '@/common/arrayutil.js'
import { getVO } from '@/common/proto-vo.js'
import {setFetchedData, KEYS} from '@/common/constFetchData.js'

/** 获取我的menu列表 */
export function getMyMenu () {
  return ax({
    method: 'post',
    data: {action: action.ACTION.CMP_MENU_MY_GETS}
  })
}

/** 获取全部的menu列表 */
export function getAllMenu () {
  return ax({
    method: 'post',
    data: {action: action.ACTION.CMP_MENU_GETS}
  })
}

/** 增加一个菜单(父菜单或者子菜单) */
export function addNewMenu (data) {
  return ax({
    method: 'post',
    data: {action: action.ACTION.CMP_MENU_ADD, data: {data: [data]}}
  })
}

/** 编辑一个菜单(父菜单或者子菜单) */
export function editMenu (data) {
  return ax({
    method: 'post',
    data: {action: action.ACTION.CMP_MENU_MODIFY, data: data}
  })
}

/** 删除一个菜单 */
export function delMenu (id) {
  return ax({
    method: 'post',
    data: {action: action.ACTION.CMP_MENU_DEL, data: {longValues: [id]}}
  })
}

/** 根据返回的数据，生成vo的列表 */
export function getMenuVOList (data) {
  let MenuVO = getVO('MenuVO')
  let vos = []
  let pv = data.data.data
  let len = pv.data.length
  for (let i = 0; i < len; i++) {
    let vo = MenuVO.decode(pv.data[i])
    let menuvo = createMenuVO(vo)
    vos.push(menuvo)
  }
  let menuAll = createMenuList(vos)
  // 此处将获得的带子级的列表数据缓存
  setFetchedData(KEYS.ALL_MENUS, menuAll)
  return menuAll
}

/** 通过menu接口回来的menuvo来生成标准vo */
export function createMenuVO (vo) {
  let menuvo = {
    id: vo.id.toNumber(),
    menuAction: vo.menuAction,
    menuName: vo.menuName,
    name: vo.name,
    parentId: parseFloat(vo.parentId),
    sort: vo.sort,
    isHidden: vo.isHidden,
    routerPath: trim(vo.menuName),
    mid: '' + vo.id.toNumber(),
    children: []
  }
  return menuvo
}

/** 这里通过发过来的Menu列表，生成带有子级的菜单列表 */
export function createMenuList (vos) {
  vos.sort(function (a, b) {
    return a.parentId - b.parentId
  })
  let menuAll = []
  let len = vos.length
  for (let i = 0; i < len; i++) {
    let mvo = vos[i]
    if (mvo.parentId === 0) {
      menuAll.push(mvo)
    } else {
      let pmvo = getListItemByKey(menuAll, 'id', mvo.parentId)
      if (pmvo) {
        pmvo.children.push(mvo)
      }
    }
  }
  menuAll.sort(function (a, b) {
    return a.sort - b.sort
  })
  for (let i = 0; i < menuAll.length; i++) {
    if (menuAll[i].children.length > 0) {
      menuAll[i].children.sort(function (a, b) {
        return a.sort - b.sort
      })
    }
  }
  return menuAll
}
